import { Component, OnInit } from "@angular/core";
import { _HttpClient, ModalHelper } from "@delon/theme";
import { NzMessageService, NzModalService, NzModalSubject } from "ng-zorro-antd";
import { tap } from "rxjs/operators";
import { TestTableEditComponent } from "./test-table-edit.component";

@Component({
    selector: 'test-table-list',
    templateUrl: './test-table-list.component.html'
})
export class TestTableListComponent implements OnInit {
    pageQuery: any = {
        pageIndex: 1,
        pageSize: 10,
        sorter: '',
        status: null,
        statusList: []
    };

    data: any[] = [];  
    curRows: any[] = [];
    selectedRows: any[] = [];
    sortMap: any = {};
    totalCallNo = 0
    expandForm = false;
    modalVisible = false;
    description = '';
    indeterminate = false;
    allChecked = false;
    loading = false;

    isConfirmLoading = false;
    currentModal;
    status = [
        { text: '关闭', value: false, type: 'default' },
        { text: '运行中', value: false, type: 'processing' },
        { text: '已上线', value: false, type: 'success' },
        { text: '异常', value: false, type: 'error' }
    ]

    constructor(private http: _HttpClient,
                public msg: NzMessageService,
                private modalHelper: ModalHelper,
                private modalService: NzModalService,
                private subject: NzModalSubject
                ) {}


    /**
     * 初始化
     */
    ngOnInit() {
        this.getData();
    }

    /**
     * 获取数据
     */
    getData() {
        this.pageChange(1).then(() => {
            this.pageQuery.statusList = this.status.map((i, index) => i.value ? index : -1).filter(w => w !== -1);
            if (this.pageQuery.status !== null && this.pageQuery.status > -1) {
                this.pageQuery.statusList.push(this.pageQuery.status);
            } 
            this.http.get("/rule", this.pageQuery).pipe(
                tap((list: any[]) => {
                    return list.map(i => {
                        const statusItem = this.status[i.status];
                        i.statusText = statusItem.text;
                        i.statusType = statusItem.type;
                        i.KKK = "我爱你就像老鼠爱大米";
                        return i;
                    });
                })
            ).subscribe(res => this.data = res)
            
        });
    }

    /**
     * 全选
     * @param value 是否选中
     */
    checkAll(value: boolean) {        
        this.curRows.forEach(i => {
            if (!i.disabled) {
                i.checked = value;
            }
        })
        this.refreshStatus()
    }

    /** 
     * 刷新状态 
     */
    refreshStatus() {
        const allChecked = this.curRows.every(i => i.disabled || i.checked);
        const allUnChecked =  this.curRows.every(i => i.disabled || !i.checked);
        this.allChecked = allChecked;
        this.indeterminate = (!allChecked) && (!allUnChecked);
        this.selectedRows = this.curRows.filter(i => i.checked);
        this.totalCallNo = this.selectedRows.reduce((total, cv) => total+cv.callNo, 0);
    }

    /**
     * 数据变更
     * @param res 
     */
    dataChange(res: any) {
        this.curRows = res
        this.refreshStatus()
    }

    /**
     * 页码变更
     * @param pageIndex 页码
     */
    pageChange(pageIndex: number): Promise<any> {
        this.pageQuery.pageIndex = pageIndex
        this.loading = true
        return new Promise(resolve => {
            setTimeout(() => {
                this.loading = false;
                resolve();
            }, 500);
        });
    }
    
    /**
     * 重置
     * @param list 状态列表
     */
    reset(list: any[]) {
        for (const i of list) {
            i.value = false;
        }
        this.getData();
    }

    /**
     * 排序
     * @param field 编号
     * @param value 值
     */
    sort(field: string, value: any) {
        this.sortMap = {};
        this.sortMap[field] = value;
        this.pageQuery.sorter = value ? `${field}_${value}` : "";
        this.getData();
    }

    /**
     * 清空
     */
    clear() {
        this.selectedRows = []
        this.totalCallNo = 0
        this.curRows.forEach(i => i.Checked = false)
        this.refreshStatus()
    }


    /** 
     * 添加弹出层 
     */
    add() : void {
        this.modalVisible = true;
        this.description = '';
    }

    /** 
     * 取消弹出层 
     */
    cancel(): void {
        this.modalVisible = false;
        this.description = '';
    }

    /**
     * 配置弹出层
     * @param obj 
     */
    setConfig(no: string) {
        this.modalHelper.open(TestTableEditComponent,  { no: no }).subscribe(() => {
            console.log("打开配置弹出层");
            
        })
    }

    /**
     * 修改弹出层
     * @param tempContent 
     */
    setModify(tempContent) {
        this.modalService.open({
            title: "修改弹出层",
            content: tempContent,
            okText: "确定",
            cancelText: "取消",
            closable: true,
            showConfirmLoading: true,
            onOk: () => {
                // 确定后的回调
                return new Promise((resolve) => {
                    this.msg.success("确定");
                    setTimeout(() => {
                        resolve();
                    }, 1000);
                });
            },
            onCancel: () => {
                //取消后的回调
                return new Promise((resolve) => {
                    this.msg.success("取消");
                    setTimeout(resolve, 1000);
                });

            }
            
        })
    }

    /**
     * 更新弹出层
     * @param tempContent 
     */
    setUpdate(tempTitle, tempContent, tempfooter) {
        this.currentModal =   this.modalService.open({
            title: tempTitle,
            content: tempContent,
            footer: tempfooter,
            maskClosable: false,
            
            onOk: () => {
                //确定后的回调
                this.msg.success("保存");
            },
            onCancel: () => {
                this.msg.success("取消");
            }
        })
    }

    /** 
     * 关闭更新弹出层 
     */
    closeUpdateModal() {
        this.isConfirmLoading = true;
        setTimeout(() => {
            this.currentModal.destroy();
            this.isConfirmLoading = false;
            this.currentModal = null;
        }, 1000);
    }


    /**
     * 保存更新弹出层 
     */
    saveUpdateModel() {
        this.isConfirmLoading = true;
        setTimeout(() => {
            this.currentModal.destroy('onOk');
            this.isConfirmLoading = false;
            this.currentModal = null;
        }, 1000);

    }
}